package com.xuyuan.json.jackson.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

@Configuration
public class ObjectMapperConfig {
    @Primary
    @Bean
    public ObjectMapper getObjectMapper() {
        InjectableValues.Std injectableValues = new InjectableValues.Std();
        injectableValues.addValue("responseTime", new Date());
        // ObjectMapper mapper = new ObjectMapper();
        // mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        // mapper.setTimeZone(TimeZone.getTimeZone("UTC+8"));
        // mapper.setLocale(Locale.CHINA);
        // mapper.setInjectableValues(injectableValues);
        //
        // mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
        // mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        // mapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true); // mapper.enable(MapperFeature.PROPAGATE_TRANSIENT_MARKER);
        // mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        // mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
        // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        return JsonMapper.builder()
                .defaultDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                .defaultTimeZone(TimeZone.getTimeZone("UTC+8"))
                .defaultLocale(Locale.CHINA)
                .injectableValues(injectableValues)
                .enable(JsonParser.Feature.AUTO_CLOSE_SOURCE)
                .enable(SerializationFeature.INDENT_OUTPUT)
                // 忽略transient字段
                .enable(MapperFeature.PROPAGATE_TRANSIENT_MARKER)
                .disable(SerializationFeature.WRAP_ROOT_VALUE)
                .disable(DeserializationFeature.UNWRAP_ROOT_VALUE)
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                .build();
    }
}
